<template>
  <div class="search-container">
    <!-- 搜索栏 -->
    <!--
      Tips: 在 van-search 外层增加 form 标签，且 action 不为空，即可在 iOS 输入法中显示搜索按钮
     -->
    <form action="/">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch(searchText)"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
    </form>
        <!-- /搜索栏 -->

    <!-- 搜索结果 -->
    <search-result :search-text="searchText" v-if="isResultShow" />
    <!-- /搜索结果 -->

    <!-- 联想建议 -->
    <search-suggestion
     :search-text="searchText"
     v-else-if="searchText"
     @search="onSearch"/>
    <!-- /联想建议 -->

    <!-- 搜索历史记录 -->
    <search-history
     :search-histories="searchHistories"
     @update-histories="searchHistories=$event"
     @search="onSearch"
      v-else/>
    <!-- /搜索历史记录 -->
  </div>
</template>

<script>
import SearchHistory from './components/search-history'
import SearchSuggestion from './components/search-suggestion'
import SearchResult from './components/search-result'
import { setItem, getItem } from '@/utils/storage'
// import { getUserSearchHistory } from '@/api/search'
import { mapState } from 'vuex'
export default {
  name: 'SearchIndex',
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  },
  props: {},
  data () {
    return {
      searchText: '',
      isResultShow: false, // 控制搜索结果的显示状态
      searchHistories: getItem('search-histories') || []
    }
  },
  computed: {
    ...mapState(['user'])
  },
  watch: {
    searchHistories () {
      // 同步到本地存储
      setItem('serach-histories', this.searchHistories)
    }
  },
  created () {
    this.loadSearchHistory()
  },
  mounted () {},
  methods: {
    onSearch (searchText) {
      this.searchText = searchText
      // 记录搜索记录
      const index = this.searchHistories.indexOf(searchText)
      if (index !== -1) {
        this.searchHistories.splice(index, 1)
      }
      this.searchHistories.unshift(searchText)
      // 登录则存储线上 否则就是存储到本地
      // setItem('search-histories', this.searchHistories)
      this.isResultShow = true
    },
    onCancel () {
      this.$router.back()
    },
    async loadSearchHistory () {
      const SearchHistory = getItem('search-histories') || [] // 本地
      // if (this.user) {
      //   const { data } = await getUserSearchHistory() // 线上
      //   // ...数组合并
      //   SearchHistory = [...new Set([...SearchHistory, ...data.data.keywords])]
      // }
      this.searchHistories = SearchHistory
    }
  }
}
</script>

<style scoped lang="less"></style>
